<template>
  <div class="width-100 height-100 ppp-pie" ref="container" v-loading="loading">
    <v-chart ref="chart" :option="option" style="width:100%;height:60%;"></v-chart>
    <div class="chart-content text-center width-100">
      <ol style="padding-left: 0;">
        <li style="line-height: 2;font-size: 1.1rem;" v-for="(item, index) in data" :key="item.name" :style="{color: colors[index]}">{{item.name}}</li>
      </ol>
    </div>
  </div>
</template>

<style scoped>
.ppp-pie {
  display: flex;
  flex-direction: column;
}
.chart-content {
  flex: 0 0 40%;
}
.chart-content li {
  list-style-position: inside;
}
</style>

<script>
import ChartResizeListener from '@/mixins/chart-resize-listener';
import MixinChartOptionToolbox from '@/mixins/chart-option-toolbox';
import { pieTooltipFormatter, defaultNumber } from '@/utils';

export default {
  name: 'pie-chart',
  mixins: [ChartResizeListener, MixinChartOptionToolbox],
  props: {
    title: String,
    colors: {
      type: Array,
      default () {
        return ['#0037c8', '#1378e0', '#35abb9', '#4ba61a', '#9cbb16', '#d0a71b']
      }
    },
    data: {
      type: Array,
      default () {
        return []
      }
    },
    downloadFunc: Function,
    showDownloadTool: Boolean
  },
  data () {
    return {
      loading: false
    }
  },
  computed: {
    option () {
      const data = this.data
      const colors = this.colors
      data.sort((a, b) => b.value - a.value)
      const title = this.title
      return {
        title: {
          text: title,
          textStyle: {
            fontWeight: 'normal'
          }
        },
        tooltip: {
          show: true,
          formatter: pieTooltipFormatter
        },
        toolbox: this.getChartOptionToolbox({
          feature: {
            magicType: null,
          }
        }),
        legend: {
          show: false,
          bottom: '20px',
          left: 'center',
          textStyle: {
            fontSize: 0
          },
        },
        series: [
          {
            type: 'pie',
            radius: ['36%', '60%'],
            center: ['50%', '60%'],
            label: {
              show: false
            },
            name: title,
            data: data.map((v, i) => ({
              ...v,
              itemStyle: {
                color: colors[i]
              }
            })),
          }
        ]
      }
    },
  },
  methods: {
    setLoading (loading) {
      this.loading = loading
    },
    optionToContent (opt) {
      try {
        const data = [
          ['企业名称', '单位', '数值'],
          ...opt.series[0].data.map(item => [item.name, item.unit, defaultNumber(item.value)])
        ];
        return this.generateTable(data);
      } catch (e) {
        console.warn(e)
      }
    }
  },
}
</script>
